package com.zhitan.ems.plat.web.controller.common;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zhitan.ems.common.core.domain.R;
import com.zhitan.ems.common.extra.utils.Base64Util;
import com.zhitan.ems.oss.utils.OssUtils;

import cn.hutool.core.lang.UUID;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
@Api(tags = "通用文件上传接口")
@Slf4j
@RestController
@RequestMapping("/common/oss")
public class OssUploadController {
	 @ApiOperation("文件上传")
	@PostMapping("/upload")
	public Object upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			return R.error("文件不能为空");
		}
		// 上传文件
		String url =OssUtils.uploadFile(file);
		log.info("--------url---------" + url);
		return R.data(url);
	}
	 @ApiOperation("文件带路径上传")
	@ResponseBody
	@PostMapping("/toupload/{osspath}")
	public R<Map<String,Object>> toupload(@RequestParam("file") MultipartFile file, @PathVariable("osspath") String osspath)
			throws Exception {
		if (file.isEmpty()) {
			return R.error("文件不能为空");
		}
		// 上传文件
		String fileName = file.getOriginalFilename();
		String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
		String pathAndfileName=osspath+"/"+ UUID.fastUUID() + "." + extensionName;
		String url =OssUtils.uploadFile(file,pathAndfileName);
		String fileSize = file.getSize() + "";
		Map<String,Object> r = new HashMap<String, Object>();
		r.put("url", url);
		r.put("link", url);
		r.put("fileName", fileName);
		r.put("extensionName", extensionName);
		r.put("fileSize", fileSize);
		return R.data(r);
	}
	 @ApiOperation("文件base64上传")
	@PostMapping("/uploadbase64")
	public R<String> uploadbase64(@RequestParam("base64img") String base64img) throws Exception {
		if (base64img == null) {
			return R.error("数据不能为空");
		}
		String prefix = "jpg";
		String imgBase64 = base64img;
		if (base64img.contains(",")) {
			String data[] = base64img.split(",");
			String fileName = data[0];
			prefix = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.lastIndexOf(";"));
			imgBase64 = data[data.length - 1];
		}
		// 上传文件
		String pathAndName = UUID.fastUUID() + "." + prefix;
		InputStream inputStream=new ByteArrayInputStream(Base64Util.strToByte(imgBase64));
		String url =OssUtils.uploadFile(inputStream, pathAndName, "image/jpeg");
		log.info("--------url---------" + url);
		return R.data(url);
	}

}